<?php
/**
 * Created by PhpStorm.
 * User: yafex
 * Date: 2019/10/28
 * Time: 10:13
 */
class serv_rapi_ali extends L {

    public static $imgUrl = "https://cbu01.alicdn.com/";

    public static $account = 'today186';

    /**
     * 描述: 获取1688平台的产品明细信息
     * 作者：Zoro.Zhu
    **/
    public static function getProduct($productId = null, $account = null){
        core_base::trans(null);                                             //开启事务
        $token = model_vsAccount::getAccountToken(array('account' => self::$account));
        $token['productId'] = $productId;
        $productInfo = model_api_aliApi::getProduct($token);
//        of::slashesDeep($productInfo);yyw
        $isConsignMarketOffer = 0;
        if(!empty($productInfo['bizGroupInfos'])){
            foreach ($productInfo['bizGroupInfos'] as $row){
                //该产品是否为1688代销产品
                if($row['code'] == 'isConsignMarketOffer' && $row['support'] === true){
                    $isConsignMarketOffer = 1;
                    break;
                }
            }
        }
        if($isConsignMarketOffer === 0){
            return '该产品不是1688代销产品';
        }
        if(!empty($productInfo['productInfo']['categoryID'])){
            $token['categoryId'] = $productInfo['productInfo']['categoryID'];
            $catName = model_api_aliApi::getCatInfo($token);
            !empty($catName['categoryInfo'][0]['name']) && $productInfo['productInfo']['categoryName'] = $catName['categoryInfo'][0]['name'];
        }
        core_ali::setProduct($productInfo, $account);
        $result = core_base::trans(true);
        if($result['state']){
            //设置上传图片到pdd的消息队列，上传图片后再进行刊登到pdd
            of_base_com_mq::set(array('downloadImg', $productId), array('productId' => $productId, 'account' => $account));
            return $productInfo;
        }
        return false;
    }

    /**
     * 描述 : 下载图片，按照规则保存
     * 参数 ：{
     *      ali接口返回的数据包
     * }
     * 返回值{
     *      type 类型 : [vsPath 图片路径]
     * }
     * 作者 : Zoro.Zhu
    **/
    public static function downloadImage($info) {
        $src = "/data/image/1688/" . date('ymd') . '/' . $info['productInfo']['productID'];
        $srcMain = $src . '/main/';
        $srcDetail = $src . '/detail/';
        $srcSku = $src . '/sku/';
        $imgPath = [10 => [], 20 => [], 30 => []];
        model_com::mkdirs(of::config('_of.rootDir') . $srcMain);
        model_com::mkdirs(of::config('_of.rootDir') . $srcDetail);
        model_com::mkdirs(of::config('_of.rootDir') . $srcSku);
        //下载图片并保存
        foreach($info['productInfo']['image']['images'] as $key => $url){
            $imgInfo = getimagesize(self::$imgUrl . $url);
            if($imgInfo[0] != $imgInfo[1] || $imgInfo[0] < 450 || $imgInfo[1] < 450 || $imgInfo['mime'] != 'image/jpeg'){
                continue;
            }
            $result = self::getImgInfo(['url' => self::$imgUrl . $url]);
            if($result !== false){
                $key = sprintf("%03d", $key);
                $srcPath = $srcMain . "{$key}.jpg";
                $fp2=@fopen(of::config('_of.rootDir') . $srcPath,'a');
                fwrite($fp2, $result);
                fclose($fp2);
                $imgPath[10][] = $srcPath;
            }
        }
        //一张合格的主图都没有，不要了
        if(empty($imgPath[10])){
            return '没有合格的主图';
//            return [];
        }
        //下载详情里的图片
        $description = stripslashes($info['productInfo']['description']);
        $hParseObj = new of_base_com_hParse($description);
        $imgHtml = $hParseObj->m('img')->eq();
        foreach($imgHtml as $key => $html){
            if($key >= 20){                                                     //详情图只需要20张
                break;
            }
            $imgSrc = $html->attr('src');
            if(empty($imgSrc)){
                continue;
            }
            //屏蔽动图
            if(substr($imgSrc, -3) == 'gif'){
                continue;
            }
//            echo $imgSrc . '<br>';
            $imgSrc = explode('?', $imgSrc);
            $imgSrc = $imgSrc[0];
            //详情图，图片宽度应为480-1200px，高度应为1500px以内,格式为jpeg
            $imgInfo = getimagesize($imgSrc);
            if($imgInfo[0] < 480 || $imgInfo[0] > 1200 || $imgInfo[1] > 1500 || $imgInfo['mime'] != 'image/jpeg'){
                continue;
            }
            $result = self::getImgInfo(['url' => $imgSrc]);
            //详情图下载失败忽略 todo  待优化
            if($result !== false){
                $key = sprintf("%03d", $key);
                $srcPath = $srcDetail . "{$key}.jpg";
                $fp2=@fopen(of::config('_of.rootDir') . $srcPath,'a');
                fwrite($fp2, $result);
                fclose($fp2);
                //如果轮播图小于10张，且详情图符合轮播图的标准，就晋升为轮播图
                if(count($imgPath[10]) < 10 && $imgInfo[0] == $imgInfo[1]){
                    $imgPath[10][] = $srcPath;
                }else{
                    $imgPath[20][] = $srcPath;
                }
            }
        }
        //下载SKU对应的图片
        $inImg = [];
        foreach($info['productInfo']['skuInfos'] as $key => $sku){
            foreach($sku['attributes'] as $attr){
                //图片为空，或者图片已存在的，不下载（去重）
                if(!empty($attr['skuImageUrl']) && !in_array($attr['skuImageUrl'], $inImg)){
                    $result = self::getImgInfo(['url' => self::$imgUrl . $attr['skuImageUrl']]);
                    if($result !== false){
                        $key = sprintf("%03d", $key);
                        $srcPath = $srcSku . "{$key}.jpg";
                        $fp2=@fopen(of::config('_of.rootDir') . $srcPath,'a');
                        fwrite($fp2, $result);
                        fclose($fp2);
                        $imgPath[30][] = $srcPath;
                        $inImg[] = $attr['skuImageUrl'];
                    }
                }
            }
        }
//        p($imgPath);
        return $imgPath;
    }

    /**
     * 描述 ：获取图片内容
     * 参数 ： {
     *      url ：图片地址
     *      count ：第几次抓取
     * }
     * 返回值 ：图片内容
     * 作者 ：Zoro.Zhu
    **/
    public static function getImgInfo($params){
        $result = of_base_com_net::request($params['url']);
        if(empty($result['response'])){
            if(empty($params['count']) || $params['count'] < 3){
                $params['count'] = empty($params['count']) ? 1 : $params['count'] + 1;
                return self::getImgInfo($params);
            } else {
                return false;
            }
        } else {
            return $result['response'];
        }
    }

    /**
     * 描述 : 获取ali产品信息
     * 作者 : Zoro.Zhu
     */
    public static function getAliProduct($productId){
        $token = model_vsAccount::getAccountToken(array('account' => self::$account));
        $token['productId'] = $productId;
        $productInfo = model_api_aliApi::getProduct($token);
        return $productInfo;
    }

}
return true;